<?php

namespace App\Http\Controllers\Traits;

use Illuminate\Support\Facades\Response;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;

trait JsonResponse
{
    protected $statusCode = FoundationResponse::HTTP_OK;

    protected $header = [];

    public static $resourceAdditionalMeta = [
        'msg' => 'success',
        'error' => 0,
    ];

    public function getStatusCode()
    {
        return $this->statusCode;
    }

    public function setStatusCode($statusCode)
    {
        $this->statusCode = $statusCode;
        return $this;
    }

    public function getHeader()
    {
        return $this->header;
    }

    public function setHeader(array $header)
    {
        $this->header = $header;
        return $this;
    }

    public function respond($data)
    {
        return Response::json($data, $this->getStatusCode(), $this->getHeader());
    }

    public function status($msg, $error = 0, array $data = [])
    {
        $status = [
            'msg' => $msg,
            'error' => $error,
        ];

        if ($data) $status['data'] = $data;
        return $this->respond($status);
    }

    public function message($msg, $error = 0)
    {
        return $this->status($msg, $error);
    }

    public function failed($msg, $code, $statusCode = FoundationResponse::HTTP_BAD_REQUEST)
    {
        return $this->setStatusCode($statusCode)->message($msg, $code);
    }

    public function success($data, $msg = 'success')
    {
        return $this->status($msg, 0, $data);
    }

    public function created($msg = 'created')
    {
        return $this->setStatusCode(FoundationResponse::HTTP_CREATED)->message($msg);
    }

    public function unauthorized($msg = 'Unauthorized', $code = FoundationResponse::HTTP_UNAUTHORIZED)
    {
        return $this->failed($msg, $code, FoundationResponse::HTTP_UNAUTHORIZED);
    }

    public function forbidden($msg = 'Forbidden', $code = FoundationResponse::HTTP_FORBIDDEN)
    {
        return $this->failed($msg, $code, FoundationResponse::HTTP_FORBIDDEN);
    }

    public function notFound($msg = 'Not Found', $code = FoundationResponse::HTTP_NOT_FOUND)
    {
        return $this->failed($msg, $code, FoundationResponse::HTTP_NOT_FOUND);
    }

    public function internalError($msg = 'Internal Error', $code = FoundationResponse::HTTP_INTERNAL_SERVER_ERROR)
    {
        return $this->failed($msg, $code, FoundationResponse::HTTP_INTERNAL_SERVER_ERROR);
    }
}